package com.atguigu.gmall.payment.service.impl;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.service.PaymentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * @Author LEO
 * @Date 2021年12月22日 21:57
 */
@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Autowired
    private RabbitService rabbitService;


    @Override
    public void savePaymentInfo(OrderInfo orderInfo, String paymentType) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderInfo.getId());
        queryWrapper.eq("payment_type",paymentType);
        Integer count = paymentInfoMapper.selectCount(queryWrapper);
        if (count !=0){
            return;
        }

        //插入数据到数据库
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setTotalAmount(orderInfo.getTotalAmount());
        paymentInfo.setSubject(orderInfo.getTradeBody());
        paymentInfo.setPaymentStatus(PaymentStatus.UNPAID.name());
        paymentInfoMapper.insert(paymentInfo);
    }



    @Override
    public PaymentInfo getPaymentInfo(String outTradeNo, String name) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("out_trade_no",outTradeNo);
        queryWrapper.eq("payment_type",name);
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(queryWrapper);
        return paymentInfo;
    }

    @Override
    public void paySuccess(String outTradeNo, String name, Map<String, String> paramMap) {
        // 交易记录是如何CLOSE，PAID则直接返回不需要继续处理
        PaymentInfo paymentInfoQuery = getPaymentInfo(outTradeNo, name);
       if ("CLOSE".equals(paymentInfoQuery.getPaymentStatus()) || "PAID".equals(paymentInfoQuery.getPaymentStatus())){
            return;
       }
        // trade_no   payment_status  callback_time  callback_content
        // 第一个参数：更新的内容  第二个参数：更新的条件
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setTradeNo(paramMap.get("trade_no"));
        paymentInfo.setPaymentStatus(PaymentStatus.PAID.name());
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setCallbackContent(paramMap.toString());

        UpdateWrapper<PaymentInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("out_trade_no",outTradeNo);
        updateWrapper.eq("payment_type_trade_no",outTradeNo);
        paymentInfoMapper.update(paymentInfo,updateWrapper);
//        this.updatePaymentInfo(outTradeNo,name,paymentInfo);

        // 发送消息给订单 更新订单状态：可以传递 orderId  outTradeNo
        // outTradeNo=param.get("out_trade_no")   orderId=paymentInfoQuery.getOrder()
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,MqConst.ROUTING_PAYMENT_PAY,paymentInfoQuery.getOrderId());
    }

    /**
     * 方法复用  更新交易
     * @param outTradeNo
     * @param name
     * @param paymentInfo
     */
       public void updatePaymentInfo(String outTradeNo, String name, PaymentInfo paymentInfo) {
         UpdateWrapper<PaymentInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("out_trade_no",outTradeNo);
        updateWrapper.eq("payment_type_trade_no",outTradeNo);
        paymentInfoMapper.update(paymentInfo,updateWrapper);
    }

    /**
     * 关闭交易记录
     * @param orderId
     */
    @Override
    public void closePayment(Long orderId) {
        // 在做订单的时候，什么时候才会出现在paymentInfo 中产生交易记录？在有二维码的时候才会有本地payment
        UpdateWrapper<PaymentInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id",orderId);
        Integer count = paymentInfoMapper.selectCount(updateWrapper);
        if (count==0){
            return;
        }
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setPaymentStatus(PaymentStatus.ClOSED.name());
        paymentInfoMapper.update(paymentInfo,updateWrapper);
    }
}
